<?php

namespace app\api\controller;

use app\admin\model\DataSource as DataSourceModel;
use app\admin\model\Order as OrderModel;
use app\admin\model\OrderLog as OrderLogModel;
use app\admin\model\WhatsappUser as WhatsappUserModel;
use app\common\controller\Api;
use fast\Http;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $this->success('请求成功');
    }

    public function get_data()
    {
        $dataSource = DataSourceModel::where('online', '1')->field('id,title,url,country_ids,material_id')->select();

        $saveArr = [];

        foreach ($dataSource as $key => $data) {
            $url =  $data['url'];
            $splitStr = "/index.html?token=";
            $path =  substr($url, 0, strrpos($url, $splitStr));
            $token = substr($url, strrpos($url, $splitStr) + strlen($splitStr));

            $options = [
                CURLOPT_HTTPHEADER => [
                    'Cookie: share_token=' . $token
                ]
            ];
            $response = Http::get($path . '/api_yinliu_count.html?page=1&limit=100&is_repet=1', [], $options);
            $rst = json_decode($response, true);


            // TODO 数据完整性校验
            if ($rst['code'] !== 0) {
                // $this->error('工单数据有误', $rst);
            } else {
                $active_num =  0;
                foreach ($rst['data'] as $key => $value) {

                    array_push($saveArr, [
                        'data_source_id' => $data['id'],
                        'country_ids' => $data['country_ids'],
                        'material_id' => $data['material_id'],
                        'title' => $data['title'],
                        'whatsup_url' => 'https://wa.me/' . $value['user'],
                        'whatsup_status' => $value['online'] === 1 ? 2 : 1,
                        'complete_num' => $value['day_sum'],
                        'total_num' => $rst['count'],
                    ]);

                    // 在线的
                    if ($value['online'] === 1) {
                        $active_num = $active_num + 1;
                    }
                }

                $orderModel = new OrderModel();

                // 更新统计表
                foreach ($saveArr as $key => $value) {
                    $saveArr[$key]['active_num'] = $active_num;

                    $one = $orderModel->where('whatsup_url', $value['whatsup_url'])
                        ->where('data_source_id', $value['data_source_id'])
                        ->field('id,target_num,click_num,admin_id')
                        ->find();
                    // 存在就补充id做更新，没有就新增
                    if ($one) {
                        $saveArr[$key]['id'] = $one['id'];
                        $saveArr[$key]['click_num']  = $one['click_num'];
                        $saveArr[$key]['admin_id']  = $one['admin_id'];

                        // 没分配 admin_id，就算新
                        $saveArr[$key]['new_num'] = $one['admin_id'] === 0 ? 1 : 0;

                        if ($one['target_num'] > 0 && $value['complete_num'] > 0 && $one['click_num'] > 0) {
                            $total_click_num =  $one['target_num'] / ($value['complete_num'] / $one['click_num']);    // 目标总数 /（ 当前进粉数 / 当前点击次数 ）
                            $saveArr[$key]['total_click_num'] = $total_click_num;
                            // click_num 大于 total_click_num，暂停
                            if ($total_click_num <= $one['click_num']) {
                                $saveArr[$key]['status'] = 0;   // 0 暂停
                            }
                        }
                        if ($one['click_num'] > 0) {
                            $saveArr[$key]['conversion_rate'] =  $value['complete_num'] / $one['click_num'];
                        }
                    }
                }

                $orderModel->saveAll($saveArr);

                // 存一次记录
                $orderLogModel = new OrderLogModel();
                $orderLogModel->saveAll($saveArr);
            }
        }

        $this->success('请求成功', $saveArr);
    }
}
